const { contextBridge, ipcRenderer } = require("electron")
const si = require('systeminformation');

var fs = require('fs')
var cp = require('child_process')

window.addEventListener('DOMContentLoaded', () => {

    const replaceText = (selector, text) => {
        const element = document.getElementById(selector)
        if (element) element.innerText = text
    }

    for (const type of ['chrome', 'node', 'electron']) {
        replaceText(`${type}-version`, process.versions[type])
    }
})

var themainpath;

contextBridge.exposeInMainWorld('winbase', {
    pageloader(type, cb) {
        var obj = {
            getmainpath() {
                ipcRenderer.send('getmainpath')
                ipcRenderer.on('get_mainpath', (ev, res) => {
                    themainpath = res.dev ? res.mainpath + '\\links.js' : res.mainpath + '\\public\\links.js'
                    try {
                        cb('getmainpath', require(themainpath))
                    } catch (e) {
                        cb('getmainpath', { status: 401 })
                    }
                })
            },
            getdiskmain() {
                try {
                    si.fsSize(function (data) {
                        printResults('SYNC WAY', data);
                    });
                } catch (e) {
                    console.error(e);
                }

                function printResults(title, disks) {

                    // console.log(`============ ${title} ==============\n`);

                    var arr = []

                    for (const disk of disks) {

                        arr.push({
                            name: disk.mount, percent: (
                                (disk.used / 1024 / 1024 / 1024).toFixed(2) + 'GB / ' + (disk.size / 1024 / 1024 / 1024).toFixed(2) + 'GB'
                            ), percentNum: disk.use
                        })

                        // console.log('Filesystem:', disk.filesystem);
                        // console.log('Blocks:', disk.blocks);
                        // console.log('Used:', disk.used);
                        // console.log('Available:', disk.available);
                        // console.log('Capacity:', disk.capacity);
                        // console.log('Mounted:', disk.mounted, '\n');
                    }

                    cb('getdiskmain', arr)

                    setTimeout(() => {
                        obj[type]()
                    }, 5000)

                }
            }
        }
        obj[type]()
    },
    closewins() {
        ipcRenderer.send('closewin')
    },
    getdata(cb) {
        try {
            cb({ arr: fs.readFileSync(themainpath, { encoding: 'utf8', flag: 'r' }), status: 200 })
        } catch (e) {
            cb({ status: 401 })
            fs.writeFileSync(themainpath, `
    []
                `)
        }
    },
    toweb(l) {
        cp.exec('start ' + l) //cp.exec('start Chrome http://baidu.com')
    }
})